import { ComponentClass } from 'breeze-leaf-core-lib';
import React from 'react';
import { connect, DefaultRootState } from "react-redux";
import { MetaManager } from '.';
import { viewComponent } from '../component/viewComponent';
import { setDefaultRootState } from '../factory/dataModelFactory';
import { RootProps, RootState } from '../interface/state';
import { getMetaComponent } from './metaManager';

export class RootView extends React.PureComponent<RootProps, RootState> {

  constructor(props: RootProps) {
    super(props);
    this.state = { component: null };
  }

  componentDidMount() {
    const { metaName, dispatch } = this.props;
    new MetaManager().setMetaName(metaName);
    const component = getMetaComponent(metaName);
    const componentClass = new ComponentClass(component);
    setDefaultRootState(dispatch)(componentClass.getRootState(), component);
    this.setState({ component });
  }

  render() {
    const { children } = this.props;
    const { component } = this.state;

    return (
      <React.Fragment>
        {children || component && component.view && viewComponent(component.view, this.props)}
      </React.Fragment>
    );
  }
}

export const Root = connect(state => JSON.parse(JSON.stringify(state)) as DefaultRootState)(RootView);